package com.controller;

import com.api.CommonResult;
import com.entity.*;
import com.entity.table.BUserTableDef;
import com.entity.table.FCartGoodsTableDef;
import com.entity.table.FCartTableDef;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.service.FAddressService;
import com.service.FCartGoodsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.service.FCartService;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 *  控制层。
 *
 * @author admin
 * @since 2024-06-06
 */
@Controller
@RequestMapping("/fCart")
public class FCartController {

    @Autowired
    private FCartService fCartService;
    @Autowired
    private FCartGoodsService fCartGoodsService;
    @Autowired
    private FAddressService fAddressService;

    /**
     * 添加。
     *
     * @param fCart 
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    @ResponseBody
    @Transactional
    public CommonResult save(FCart fCart, int goodId, HttpServletRequest request) {
        try {
            HttpSession session=request.getSession();
            FUser user=(FUser) session.getAttribute("user");
            fCart.setUserId(user.getId());
            FCart fCart1=fCartService.getUserCartInfo(user.getId());
            if (fCart1!=null){
                Optional<BGoods> bGoods=fCart1.getGoods().stream()
                        .filter(item -> item.getId().equals(goodId)).findFirst();
                if (bGoods.isPresent()){
                    QueryWrapper query=QueryWrapper.create().where(FCartGoodsTableDef.F_CART_GOODS.GOODS_ID.eq(goodId))
                            .and(FCartGoodsTableDef.F_CART_GOODS.CART_ID.eq(fCart1.getId()));
                    FCartGoods fCartGoods=fCartGoodsService.getOne(query);
                    fCartGoods.setNum(fCartGoods.getNum()+fCart.getNum());
                    fCartGoodsService.updateById(fCartGoods);
                }else {
                    FCartGoods fCartGoods=new FCartGoods();
                    fCartGoods.setCartId(fCart.getId());
                    fCartGoods.setCartId(goodId);
                    fCartGoods.setNum(fCart.getNum());
                    fCartGoodsService.save(fCartGoods);
                }
                fCart1.setNum(fCart1.getNum()+fCart.getNum());
                fCartService.updateById(fCart1);
            }else {
               FCart newCart=new FCart();
               newCart.setNum(fCart.getNum());
               newCart.setUserId(user.getId());
               fCartService.save(newCart);
               FCartGoods fCartGoods=new FCartGoods();
               fCartGoods.setCartId(newCart.getId());
               fCartGoods.setGoodsId(goodId);
               fCartGoods.setNum(fCart.getNum());
               fCartGoodsService.save(fCartGoods);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            CommonResult.failed("添加购物车失败");
        }
        return CommonResult.success("商品已添加购物车");
    }
    @GetMapping(value = "")
    public String List(Model model, HttpServletRequest request){
        try {
            HttpSession session = request.getSession();
            FUser user = (FUser) session.getAttribute("user");
            QueryWrapper query = QueryWrapper.create().where(FCartTableDef.F_CART.USER_ID.eq(user.getId()));
            FCart fCart = fCartService.getMapper().selectOneWithRelationsByQuery(query);
            if (fCart != null) {
                BigDecimal totalPrice = new BigDecimal(0);
                for (BGoods good : fCart.getGoods()) {
                    BGoods good1 = fCartGoodsService.getTotalPriceByGood(fCart.getId(), good);
                    totalPrice = totalPrice.add(good1.getTotalPrice());
                }
                fCart.setTotalPrice(totalPrice);
            }

            model.addAttribute("user", user);
            model.addAttribute("cart", fCart);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "client/cart";
    }
    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return fCartService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param fCart 
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody FCart fCart) {
        return fCartService.updateById(fCart);
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<FCart> list() {
        return fCartService.list();
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public FCart getInfo(@PathVariable Serializable id) {
        return fCartService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<FCart> page(Page<FCart> page) {
        return fCartService.page(page);
    }

}
